package com.repro.lib_base.utils

import com.google.gson.internal.`$Gson$Types`
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.util.*


object FindClassUtils {
    fun newParameterizedTypeWithOwner(rawType: Type?, typeArguments: Type?): Type? {
        return `$Gson$Types`.newParameterizedTypeWithOwner(null, rawType, typeArguments)
    }
    /**
     * find the type by interfaces
     * 通过反射获取到type类型
     *
     * @param cls
     * @param <R>
     * @return
    </R> */
    fun <R> findNeedType(cls: Class<R>): Type? {
        val typeList: MutableList<Type>? = getMethodTypes(cls)
        return if (typeList == null || typeList.isEmpty()) {
            null
        } else typeList[0]
    }

    /**
     * MethodHandler
     */
    fun <T> getMethodTypes(cls: Class<T>): MutableList<Type>? {
        val typeOri: Type? = cls.genericSuperclass
        var needTypes: MutableList<Type>? = null
        // if Type is T
        if (typeOri is ParameterizedType) {
            needTypes = ArrayList()
            val parenTypes: Array<Type> = (typeOri as ParameterizedType).actualTypeArguments
            for (childType in parenTypes) {
                needTypes.add(childType)
                if (childType is ParameterizedType) {
                    val childTypes: Array<Type> =
                        (childType as ParameterizedType).actualTypeArguments
                    for (type in childTypes) {
                        needTypes.add(type)
                    }
                }
            }
        }
        return needTypes
    }
}